package com.yonglian.management.web.rest;

import static com.yonglian.management.domain.ProjectBaseInfoAsserts.*;
import static com.yonglian.management.web.rest.TestUtil.createUpdateProxyForBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonglian.management.IntegrationTest;
import com.yonglian.management.domain.ProjectBaseInfo;
import com.yonglian.management.repository.ProjectBaseInfoRepository;
import jakarta.persistence.EntityManager;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link ProjectBaseInfoResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ProjectBaseInfoResourceIT {

    private static final String DEFAULT_PROJECT_NAME = "AAAAAAAAAA";
    private static final String UPDATED_PROJECT_NAME = "BBBBBBBBBB";

    private static final String DEFAULT_PROJECT_MANAGER = "AAAAAAAAAA";
    private static final String UPDATED_PROJECT_MANAGER = "BBBBBBBBBB";

    private static final String DEFAULT_PROJECT_LOCATION = "AAAAAAAAAA";
    private static final String UPDATED_PROJECT_LOCATION = "BBBBBBBBBB";

    private static final Integer DEFAULT_AMOUNT = 1;
    private static final Integer UPDATED_AMOUNT = 2;

    private static final String ENTITY_API_URL = "/api/project-base-infos";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private ObjectMapper om;

    @Autowired
    private ProjectBaseInfoRepository projectBaseInfoRepository;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restProjectBaseInfoMockMvc;

    private ProjectBaseInfo projectBaseInfo;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ProjectBaseInfo createEntity(EntityManager em) {
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo()
            .projectName(DEFAULT_PROJECT_NAME)
            .projectManager(DEFAULT_PROJECT_MANAGER)
            .projectLocation(DEFAULT_PROJECT_LOCATION)
            .amount(DEFAULT_AMOUNT);
        return projectBaseInfo;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ProjectBaseInfo createUpdatedEntity(EntityManager em) {
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo()
            .projectName(UPDATED_PROJECT_NAME)
            .projectManager(UPDATED_PROJECT_MANAGER)
            .projectLocation(UPDATED_PROJECT_LOCATION)
            .amount(UPDATED_AMOUNT);
        return projectBaseInfo;
    }

    @BeforeEach
    public void initTest() {
        projectBaseInfo = createEntity(em);
    }

    @Test
    @Transactional
    void createProjectBaseInfo() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the ProjectBaseInfo
        var returnedProjectBaseInfo = om.readValue(
            restProjectBaseInfoMockMvc
                .perform(
                    post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(projectBaseInfo))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            ProjectBaseInfo.class
        );

        // Validate the ProjectBaseInfo in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        assertProjectBaseInfoUpdatableFieldsEquals(returnedProjectBaseInfo, getPersistedProjectBaseInfo(returnedProjectBaseInfo));
    }

    @Test
    @Transactional
    void createProjectBaseInfoWithExistingId() throws Exception {
        // Create the ProjectBaseInfo with an existing ID
        projectBaseInfo.setId(1L);

        long databaseSizeBeforeCreate = getRepositoryCount();

        // An entity with an existing ID cannot be created, so this API call must fail
        restProjectBaseInfoMockMvc
            .perform(
                post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isBadRequest());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void checkProjectNameIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        projectBaseInfo.setProjectName(null);

        // Create the ProjectBaseInfo, which fails.

        restProjectBaseInfoMockMvc
            .perform(
                post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isBadRequest());

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllProjectBaseInfos() throws Exception {
        // Initialize the database
        projectBaseInfoRepository.saveAndFlush(projectBaseInfo);

        // Get all the projectBaseInfoList
        restProjectBaseInfoMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(projectBaseInfo.getId().intValue())))
            .andExpect(jsonPath("$.[*].projectName").value(hasItem(DEFAULT_PROJECT_NAME)))
            .andExpect(jsonPath("$.[*].projectManager").value(hasItem(DEFAULT_PROJECT_MANAGER)))
            .andExpect(jsonPath("$.[*].projectLocation").value(hasItem(DEFAULT_PROJECT_LOCATION)))
            .andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT)));
    }

    @Test
    @Transactional
    void getProjectBaseInfo() throws Exception {
        // Initialize the database
        projectBaseInfoRepository.saveAndFlush(projectBaseInfo);

        // Get the projectBaseInfo
        restProjectBaseInfoMockMvc
            .perform(get(ENTITY_API_URL_ID, projectBaseInfo.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(projectBaseInfo.getId().intValue()))
            .andExpect(jsonPath("$.projectName").value(DEFAULT_PROJECT_NAME))
            .andExpect(jsonPath("$.projectManager").value(DEFAULT_PROJECT_MANAGER))
            .andExpect(jsonPath("$.projectLocation").value(DEFAULT_PROJECT_LOCATION))
            .andExpect(jsonPath("$.amount").value(DEFAULT_AMOUNT));
    }

    @Test
    @Transactional
    void getNonExistingProjectBaseInfo() throws Exception {
        // Get the projectBaseInfo
        restProjectBaseInfoMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putExistingProjectBaseInfo() throws Exception {
        // Initialize the database
        projectBaseInfoRepository.saveAndFlush(projectBaseInfo);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the projectBaseInfo
        ProjectBaseInfo updatedProjectBaseInfo = projectBaseInfoRepository.findById(projectBaseInfo.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedProjectBaseInfo are not directly saved in db
        em.detach(updatedProjectBaseInfo);
        updatedProjectBaseInfo
            .projectName(UPDATED_PROJECT_NAME)
            .projectManager(UPDATED_PROJECT_MANAGER)
            .projectLocation(UPDATED_PROJECT_LOCATION)
            .amount(UPDATED_AMOUNT);

        restProjectBaseInfoMockMvc
            .perform(
                put(ENTITY_API_URL_ID, updatedProjectBaseInfo.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(updatedProjectBaseInfo))
            )
            .andExpect(status().isOk());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedProjectBaseInfoToMatchAllProperties(updatedProjectBaseInfo);
    }

    @Test
    @Transactional
    void putNonExistingProjectBaseInfo() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        projectBaseInfo.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restProjectBaseInfoMockMvc
            .perform(
                put(ENTITY_API_URL_ID, projectBaseInfo.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isBadRequest());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchProjectBaseInfo() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        projectBaseInfo.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restProjectBaseInfoMockMvc
            .perform(
                put(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isBadRequest());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamProjectBaseInfo() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        projectBaseInfo.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restProjectBaseInfoMockMvc
            .perform(
                put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateProjectBaseInfoWithPatch() throws Exception {
        // Initialize the database
        projectBaseInfoRepository.saveAndFlush(projectBaseInfo);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the projectBaseInfo using partial update
        ProjectBaseInfo partialUpdatedProjectBaseInfo = new ProjectBaseInfo();
        partialUpdatedProjectBaseInfo.setId(projectBaseInfo.getId());

        partialUpdatedProjectBaseInfo
            .projectManager(UPDATED_PROJECT_MANAGER)
            .projectLocation(UPDATED_PROJECT_LOCATION)
            .amount(UPDATED_AMOUNT);

        restProjectBaseInfoMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedProjectBaseInfo.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedProjectBaseInfo))
            )
            .andExpect(status().isOk());

        // Validate the ProjectBaseInfo in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertProjectBaseInfoUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedProjectBaseInfo, projectBaseInfo),
            getPersistedProjectBaseInfo(projectBaseInfo)
        );
    }

    @Test
    @Transactional
    void fullUpdateProjectBaseInfoWithPatch() throws Exception {
        // Initialize the database
        projectBaseInfoRepository.saveAndFlush(projectBaseInfo);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the projectBaseInfo using partial update
        ProjectBaseInfo partialUpdatedProjectBaseInfo = new ProjectBaseInfo();
        partialUpdatedProjectBaseInfo.setId(projectBaseInfo.getId());

        partialUpdatedProjectBaseInfo
            .projectName(UPDATED_PROJECT_NAME)
            .projectManager(UPDATED_PROJECT_MANAGER)
            .projectLocation(UPDATED_PROJECT_LOCATION)
            .amount(UPDATED_AMOUNT);

        restProjectBaseInfoMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedProjectBaseInfo.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedProjectBaseInfo))
            )
            .andExpect(status().isOk());

        // Validate the ProjectBaseInfo in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertProjectBaseInfoUpdatableFieldsEquals(
            partialUpdatedProjectBaseInfo,
            getPersistedProjectBaseInfo(partialUpdatedProjectBaseInfo)
        );
    }

    @Test
    @Transactional
    void patchNonExistingProjectBaseInfo() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        projectBaseInfo.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restProjectBaseInfoMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, projectBaseInfo.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isBadRequest());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchProjectBaseInfo() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        projectBaseInfo.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restProjectBaseInfoMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isBadRequest());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamProjectBaseInfo() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        projectBaseInfo.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restProjectBaseInfoMockMvc
            .perform(
                patch(ENTITY_API_URL)
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(projectBaseInfo))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ProjectBaseInfo in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteProjectBaseInfo() throws Exception {
        // Initialize the database
        projectBaseInfoRepository.saveAndFlush(projectBaseInfo);

        long databaseSizeBeforeDelete = getRepositoryCount();

        // Delete the projectBaseInfo
        restProjectBaseInfoMockMvc
            .perform(delete(ENTITY_API_URL_ID, projectBaseInfo.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
    }

    protected long getRepositoryCount() {
        return projectBaseInfoRepository.count();
    }

    protected void assertIncrementedRepositoryCount(long countBefore) {
        assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
    }

    protected void assertDecrementedRepositoryCount(long countBefore) {
        assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
    }

    protected void assertSameRepositoryCount(long countBefore) {
        assertThat(countBefore).isEqualTo(getRepositoryCount());
    }

    protected ProjectBaseInfo getPersistedProjectBaseInfo(ProjectBaseInfo projectBaseInfo) {
        return projectBaseInfoRepository.findById(projectBaseInfo.getId()).orElseThrow();
    }

    protected void assertPersistedProjectBaseInfoToMatchAllProperties(ProjectBaseInfo expectedProjectBaseInfo) {
        assertProjectBaseInfoAllPropertiesEquals(expectedProjectBaseInfo, getPersistedProjectBaseInfo(expectedProjectBaseInfo));
    }

    protected void assertPersistedProjectBaseInfoToMatchUpdatableProperties(ProjectBaseInfo expectedProjectBaseInfo) {
        assertProjectBaseInfoAllUpdatablePropertiesEquals(expectedProjectBaseInfo, getPersistedProjectBaseInfo(expectedProjectBaseInfo));
    }
}
